<!-- 非项目付款合同 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
			<view class="basic-style">
			  <view class="basic-title basic-border pt-1">供方信息</view>
			  <u-form-item label="供应商名称" prop="supplyCompanName" required>
			    <h-select-customer-input-popup
			      style="width: 100%"
			      commercialType="2"
					:isJudge='true'
					@onJudge='onJudge'
			      v-model="model.supplyCompanName"
			      border="surround"
			      placeholder="请选择供应商名称"
			      suffixIcon="arrow-down-fill"
			      :suffixIconStyle="{ color: '#B2B2B2' }"/>
				<u-icon style="margin-left: 10upx;" name="plus" color="#2979ff" size="24" @click="getUnSupplier"/>
			  </u-form-item>
			  <u-form-item label="公司地址" prop="supplyCompanyAddress" required>
			    <u--input placeholder="请输入公司地址" v-model="model.supplyCompanyAddress" />
			  </u-form-item>
			  <u-form-item label="委托代理人" prop="supplyEntrustedAgent" required>
			    <u--input placeholder="请输入委托代理人" v-model="model.supplyEntrustedAgent" />
			  </u-form-item>
			  <u-form-item label="手机号码" prop="supplyPhoneNumber" required>
			    <u--input type="number" placeholder="请输入手机号码" v-model="model.supplyPhoneNumber" />
			  </u-form-item>
			  <u-form-item label="开户银行" prop="supplyBankName" required>
			    <u--input disabled placeholder="请输入开户银行" v-model="model.supplyBankName" />
			  </u-form-item>
			  <u-form-item label="银行账号" prop="supplyBankAccountNo" required>
			    <u--input disabled placeholder="请输入银行账号" v-model="model.supplyBankAccountNo" />
			  </u-form-item>
			  <u-form-item label="纳税人识别号" prop="supplyRegistrationNumber" required>
			    <u--input disabled placeholder="请输入纳税人识别号" v-model="model.supplyRegistrationNumber" />
			  </u-form-item>
			</view>
			
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="purchaseBill" required>
          <u--input v-model="model.purchaseBill" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="propose" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
				<u-form-item label="申请时间" required>
				  <u--input v-model="model.createTime" disabled></u--input>
				</u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
				<u-form-item label="申请人所属团队" prop="applyTeam" required>
					<h-select-team-input-popup
						style="width: 100%"
						v-model="model.applyTeam"
						placeholder="请选择申请人所属团队"
						:tdlx="1"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
					></h-select-team-input-popup>
				</u-form-item>
        <u-form-item label="合同名称" prop="contractName" required>
          <u--input v-model="model.contractName" placeholder="请输入合同名称"></u--input>
        </u-form-item>
				<u-form-item label="采购类型" prop="procurementType" required>
					<h-select-input-tag
					  class="w-100"
					  v-model="model.procurementType"
					  placeholder="请选择采购类型"
					  border="surround"
					  dictName="procurement_type"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
					  @change="handleChangeProvisionType"
					></h-select-input-tag>
				</u-form-item>
				
				<view v-show="model.procurementType == '1'">
				  <u-form-item label="关联单据" prop="associationBillId" required>
				    <h-select-purchase-calibration-input-popup
				      :projectId="model.xmmc"
				      v-model="model.associationBillId"
							allowExistAll="yes"
				      placeholder="请关联定标结果确认单"
				      border="surround"
				      style="width: 100%"
							billStatus="1,2"
				      suffixIcon="arrow-down-fill"
				      :suffixIconStyle="{ color: '#B2B2B2' }"
				    />
				  </u-form-item>
				</view>
				
				<view v-show="model.procurementType == '2'">
				  <u-form-item label="关联单据" prop="associationBillId" required>
				    <h-select-purchase-apply-form-contract-input-popup
				      v-model="model.associationBillId"
				      placeholder="请关联采购申请单"
				      border="surround"
				      style="width: 100%"
				      suffixIcon="arrow-down-fill"
				      :suffixIconStyle="{ color: '#B2B2B2' }"
				    />
				  </u-form-item>
				</view>
				<view v-show="model.procurementType == '3'">
				  <u-form-item label="关联单据" prop="associationBillId" required>
				    <h-select-purchasing-requisition-input-popup
				      v-model="model.associationBillId"
				      placeholder="请关联招标采购申请单"
				      border="surround"
				      style="width: 100%"
				      suffixIcon="arrow-down-fill"
				      :suffixIconStyle="{ color: '#B2B2B2' }"
				    />
				  </u-form-item>
				</view>
				
        <u-form-item label="签订日期" prop="signingDate" required>
          <h-time-select
            mode="datetime"
            v-model="model.signingDate"
            placeholder="请选择签订日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
				<u-form-item label="定点合同" prop="isFixedTime" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.isFixedTime"
            objectField="model.isFixedTime"
            placeholder="请选择定点合同"
            border="surround"
          	suffixIcon="arrow-down-fill"
          	:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="yn"
          	@change="isFixedTimeInput"
          ></h-select-input-tag>
        </u-form-item>
				<u-form-item label="到期日期" prop="expireTime" required v-if="model.isFixedTime == 1">
          <h-time-select
            mode="datetime"
            v-model="model.expireTime"
            placeholder="请选择到期日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="合同总额(元)" prop="totalAmount">
					<h-money-input
						disabled
						placeholder="请输入合同总额"
						v-model="model.totalAmount"
					></h-money-input>
        </u-form-item>
        <u-form-item label="发票类型" prop="invoiceCategory" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.invoiceCategory"
            objectField="model. invoiceCategory"
            placeholder="请选择发票类型"
            border="surround"
            dictName="invoice_type"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            @change="invoiceCategoryBlur"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="税率(%)" prop="taxRate" required style="position: relative">
          <u--input type="number" placeholder="请输入税率" v-number-normal v-model="model.taxRate" @blur="inputTaxRateBlur" />
					<!-- <h-number-input placeholder="请输入税率" v-model="model.taxRate" :digit="0" :min="0" @blur="inputTaxRateBlur"></h-number-input> -->
          <span class="percent" style="position: absolute; right: 1em">%</span>
        </u-form-item>
        <u-form-item label="税费(元)" prop="expensesTaxation" required>
          <!-- <u--input disabled type="number" placeholder="请输入税费" v-number-normal v-model="model.expensesTaxation" /> -->
					<h-number-input disabled placeholder="请输入税费" v-model="model.expensesTaxation" :digit="2" :min="0"></h-number-input>
        </u-form-item>
        <!-- <u-form-item label="货期单位" prop="deliveryTimeUnit" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.deliveryTimeUnit"
            objectField="model.deliveryTimeUnit"
            placeholder="请选择货期单位"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="period_validity_unit"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="货期" prop="deliveryTime" required>
          <u--input type="number" placeholder="请输入货期" v-number-normal v-model="model.deliveryTime" />
        </u-form-item>
        <u-form-item label="运输方式" prop="modeTransportation" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.modeTransportation"
            objectField="model.modeTransportation"
            placeholder="请选择运输方式"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="transportation_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="运输费承担方" prop="trafficExpense" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.trafficExpense"
            objectField="model.trafficExpense"
            placeholder="请选择运输费承担方"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="transportation_bearer"
          ></h-select-input-tag>
        </u-form-item> -->
        <u-form-item label="费用所属团队" prop="teamId" required>
          <h-select-team-input-popup
            style="width: 100%"
            v-model="model.teamId"
            placeholder="请选择团队"
            :tdlx="1"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            border="surround"
            @change="teamBack"
          ></h-select-team-input-popup>
        </u-form-item>
        <u-form-item label="是否工程类" prop="isEngineering" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.isEngineering"
            objectField="model.isEngineering"
            placeholder="请选择是否工程类"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            border="surround"
            dictName="YES_OR_NO"
          ></h-select-input-tag>
        </u-form-item>
				<u-form-item label="是否用印" prop="isUseSeal" required>
				  <h-select-input-tag
				    class="w-100"
				    v-model="model.isUseSeal"
				    objectField="model.isUseSeal"
				    placeholder="请选择是否用印"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="yn"
						@change="handleRules"
				  ></h-select-input-tag>
				</u-form-item>
				<template v-if="model.isUseSeal == '1'">
					<u-form-item label="用印类型" prop="signSealWay" required>
					  <h-select-input-tag
					    class="w-100"
					    v-model="model.signSealWay"
					    objectField="model.signSealWay"
					    placeholder="请选择用印类型"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
					    border="surround"
					    dictName="seal_way"
							@change="handleSignSealWay"
					  ></h-select-input-tag>
					</u-form-item>
					<template v-if="model.isUseSeal == '1' && model.signSealWay == 'online'">
						<u-form-item label="对方是否电子签章" prop="isSignSeal" required>
							<h-dict-radio v-model="model.isSignSeal" dictName="yes_no" @input="isSignSealInput"></h-dict-radio>
						</u-form-item>
						<u-form-item v-if="model.isSignSeal && model.isSignSeal == 1" label="对方盖章人" prop="supplyPsnName" required>
							<u--input v-model="model.supplyPsnName" placeholder="请输入对方盖章人"></u--input>
						</u-form-item>
						<u-form-item v-if="model.isSignSeal && model.isSignSeal == 1" label="联系方式" prop="supplyPsnMobile" required>
							<u--input v-model="model.supplyPsnMobile" placeholder="请输入联系方式"></u--input>
						</u-form-item>
					</template>
				  <u-form-item label="印章类型" prop="sealType" required>
				    <!-- <h-select-input-tag-multi-popup
				      class="w-100"
				      v-model="model.sealType"
				      objectField="model.sealType"
				      placeholder="请选择印章类型"
				      border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{ color: '#B2B2B2' }"
				      dictName="yzlx_type"
				    ></h-select-input-tag-multi-popup> -->
						<h-dict-multi-select
							v-model="model.sealType"
							style="width: 100%" 
							placeholder="请选择印章类型"
							dictName="yzlx_type"
							border="surround"
							suffixIcon="arrow-down-fill"
							:suffixIconStyle="{color: '#B2B2B2'}"
						></h-dict-multi-select>
				  </u-form-item>
				  <u-form-item label="用印份数" prop="useSealNumber" required>
						<h-number-input placeholder="请输入用印份数" v-model="model.useSealNumber" :digit="0" :min="1"></h-number-input>
				  </u-form-item>
				</template>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border pt-1">需方信息</view>
        <u-form-item label="公司名称" prop="demandCompanName" required>
          <h-select-company-input-popup
            style="width: 100%"
            v-model="model.demandCompanName"
            border="surround"
            placeholder="请选择公司名称"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="demandCompanNameInput"
          ></h-select-company-input-popup>
        </u-form-item>
				<template v-if="model.isUseSeal == '1' && model.signSealWay == 'online'">
					<u-form-item label="我方经办人" prop="psnName" required>
						<u--input  v-model="model.psnName" placeholder="请输入我方经办人"></u--input>
					</u-form-item>
					<u-form-item label="联系方式" prop="psnMobile" required>
						<u--input  v-model="model.psnMobile" placeholder="请输入联系方式"></u--input>
					</u-form-item>
				</template>
      </view>
			
      <view class="basic-style">
        <view class="basic-title basic-border pt-1">其他信息</view>
        <u-form-item label="备注" prop="remark">
					<!-- #ifdef APP || APP-PLUS -->
					<u--textarea :confirm-type="null" count v-model="model.remark" placeholder="请输入备注" maxlength="500"></u--textarea>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<u--textarea confirm-type="done" count v-model="model.remark" placeholder="请输入备注" maxlength="500"></u--textarea>
					<!-- #endif -->
          
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border basic-flex">
					<text>付款信息</text>
					<view class="trip-form-notice">合同总额: {{ totalMoney }}元</view>
				</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="addPaymentForm">新增</u-button>
        </view>
        <view class="trip-form-data">
					<view v-for="(item, index) in paymentFormData" :key="index">
						<PaymentFormInfo
							:item="item"
							:index="index"
							@edit="handleEditPaymentForm"
							@remove="handleRemovePaymentForm"
						/>
					</view>
        </view>
        <u-popup mode="bottom" :show="showPaymentForm">
          <PaymentForm ref="dataPaymentForm" :index="index" @submit="handlePaymentFormSubmit" @close="closePaymentForm" />
        </u-popup>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">物料信息</view>
        <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="addMaterialForm">新增</u-button>
					<u-button size="small" type="primary" :disabled="isDisabled" :plain="true" @click="handleBalize">导入定标单关联采购物料清单</u-button>
					<u-button size="small" type="primary" :plain="true" @click="handleMenu">导入采购清单</u-button>
					<view style="display: flex;align-items: center;">
						<u-button size="small" type="primary" :disabled="!deleteCheck.length" :plain="true" @click="deleteAllMaterial">批量删除</u-button>
						<u-checkbox-group style="margin-left: 40rpx;" v-model="materialChecked" @change="handleCheck">
							<u-checkbox :disabled="!isDisabled"></u-checkbox>
						</u-checkbox-group>
					</view>
        </view>
				<u-checkbox-group @change="childCheck">
        <view class="trip-form-data">
					<view v-for="(item, index) in materialFormData" :key="index">
						<MaterialFormInfo
							:item="item"
							:index="index"
							@edit="handleEditMaterialForm"
							@remove="handleRemoveMaterialForm"
						>
							<template slot="check">
								<u-checkbox
									:name="item.id"
									:checked="item.checked"
								>
								</u-checkbox>
							</template>
						</MaterialFormInfo>
					</view>
        </view>
				</u-checkbox-group>
        <u-popup mode="bottom" :show="showMaterialForm" :closeOnClickOverlay="false">
          <MaterialForm ref="dataMaterialForm" :index="index" @submit="handleMaterialFormSubmit" @close="closeMaterialForm" />
        </u-popup>
      </view>
			<view class="basic-style"  v-if="model.isUseSeal == 1">
			  <view class="basic-title basic-border">用印文件<span style="color: #faad14;font-weight: 600">（请上传只需盖章的用印文件！）</span></view>
			  <u-form-item label="用印文件" prop="signFile" required>
					<view class="py-1 space-y-1" style="width: 100%">
						<view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
						<h-upload-file v-model="model.signFile" :fillSize="50" :isIcon="false" :isSingle="true" fileType=".pdf, .PDF, .doc, .docx" fileTypeText="请上传word与pdf格式的文件！"></h-upload-file>
						<file-list v-if="model.signFile" v-model="model.signFile" :isDelete="true"></file-list>
					</view>
				</u-form-item>
			</view>
			<view class="basic-style">
			  <view class="basic-title basic-border">合同原件扫描件(仅合同管理员上传)</view>
			  <view class="py-1 space-y-1" style="width: 100%">
			    <!-- <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view> -->
			    <!-- <h-upload-file v-model="model.contractOrgFile" :isIcon="false"></h-upload-file> -->
			    <file-list v-model="model.contractOrgFile"></file-list>
			  </view>
			</view>
      <view class="basic-style">
        <view class="basic-title basic-border">相关附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.purchaseFile" :isIcon="false"></h-upload-file>
          <file-list v-if="model.purchaseFile" v-model="model.purchaseFile" :isDelete="true"></file-list>
        </view>
      </view>
			
			<view class="space-x-1 px-1 btn_position">
				<u-button type="primary" text="保存" :plain="true" :disabled="isSubmit" @click="onDraft"></u-button>
			  <u-button type="primary" text="保存并提交" :disabled="isSubmit" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
		<applyFormInput ref="applyFormInput" @back="contactBack"></applyFormInput>
		<cannibalizeInput billStatus="1,2" ref="cannibalizeInput" @back="cannibalizeInputBack"></cannibalizeInput>
		<u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { gainBillNo, add, info,edit,urlListDetail } from '@/api/contract/ErpPurchaseContractForm'
import {
  queryByIdPurchaseContractSuppliesAllList, // 物料信息
	queryByIdPurchaseContractPayAllList, // 付款信息
} from '@/api/index'
import applyFormInput from './components/applyFormInput.vue'
import fileList from '@/pages/synergy/components/fileList.vue'
import cannibalizeInput from './components/cannibalizeInput.vue'
import PaymentForm from './components/PaymentForm.vue'
import PaymentFormInfo from './components/PaymentFormInfo.vue'
import MaterialForm from './components/MaterialForm.vue'
import MaterialFormInfo from './components/MaterialFormInfo.vue'
import { Decimal } from 'decimal.js'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
export default {
  name: 'ErpPurchaseContractForm',
  components: {
    PaymentForm,
		fileList,
    PaymentFormInfo,
    MaterialForm,
    MaterialFormInfo,
		applyFormInput,
		cannibalizeInput,
		ProcessNodeConfiguration,
  },
  data() {
    return {
		teamIdBackups: null,
		materialChecked: [],
		deleteCheck: [],
		index: null,
		confirmModal: false,
		id: '',
		basicPaymentForm: {},
		basicFormB: {},
		basicMaterialForm: {},
		showPaymentForm: false,
		showFormModalB: false,
		showMaterialForm: false,
		paymentFormData: [],
		materialFormData: [],
		model: {
		// 基本信息 - 公用
		bpmBizTitle: '',
		purchaseBill: '',
		proposer: '',
		proposerDeptId: '',
		createTime: '',
		applyTeam:'',
		// 基本信息 - 非公用
		masterCopy: null,
		bchte: '',
		htlx: 2,
		procurementType: '',
		signSealWay: '',
		supplyPsnName: '',
		psnName: '',
		supplyPsnMobile: '',
		psnMobile: '',
		// 附件
		purchaseFile: null,
		signFile: null
		},
		rules: {
			purchaseBill: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
			proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
			proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
			createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
			signingDate: [{ required: true, message: '请选择签订日期!', trigger: 'change' }],
			isFixedTime: [{ required: true, message: '请选择定点合同!', trigger: 'change' }],
			expireTime: [{ required: true, message: '请选择到期日期!', trigger: 'change' }],
        taxRate: [
          { required: true, message: '请输入税率!', trigger: 'blur' },
          { required: true, pattern: /^(([0-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的税率!' },
        ],
        expensesTaxation: [
          { required: true, message: '请输入税费!', trigger: 'blur' },
          { required: true, pattern: /^(([0-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' },
        ],
        invoiceCategory: [{ required: true, message: '请选择发票类型!', trigger: 'blur' }],
        deliveryTime: [
          { required: true, message: '请输入货期!', trigger: 'blur' },
          { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
        ],
        teamId: [{ required: true, message: '请选择费用所属团队!', trigger: 'change' }],
        demandCompanName: [{ required: true, message: '请选择需方公司名称!', trigger: 'change' }],
        supplyCompanName: [{ required: true, message: '请选择供方公司名称!', trigger: 'change' }],
        supplyCompanyAddress: [{ required: true, message: '请输入供方公司地址!', trigger: 'blur' }],
        supplyEntrustedAgent: [{ required: true, message: '请输入供方委托代理人!', trigger: 'blur' }],
        supplyPhoneNumber: [
          { required: true, message: '请输入供方手机号码!', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!',trigger: ['blur','change'] },
        ],
        supplyBankName: [{ required: true, message: '请输入供方开户银行!', trigger: 'blur' }],
        supplyBankAccountNo: [
          { required: true, message: '请输入供方银行账号!', trigger: 'blur' }
        ],
        supplyRegistrationNumber: [{ required: true, message: '请输入供方纳税人识别号!', trigger: 'blur' }],
        isProject: [{ required: true, message: '请选择是否关联项目!', trigger: 'blur' }],
        isEngineering: [{ required: true, message: '请选择是否工程类!', trigger: 'blur' }],
				isUseSeal: [ { required: true, message: '请选择是否用印!', trigger: ['blur', 'change'] } ],
				signSealWay: [ { required: true, message: '请选择用印类型!', trigger: ['blur', 'change'] } ],
				isSignSeal: [ { required: true, message: '请选择对方是否电子签章!', trigger: ['blur', 'change'] } ],
				supplyPsnName: [ { required: true, message: '请输入人员姓名!', trigger: ['blur'] } ],
				supplyPsnMobile: [
					{ required: true, message: '请输入联系方式!' },
					{ pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!', trigger: ['blur', 'change'] }
				],
				psnName: [ { required: true, message: '请输入人员姓名!', trigger: ['blur'] } ],
				psnMobile: [
					{ required: true, message: '请输入联系方式!' },
					{ pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!', trigger: ['blur', 'change'] }
				],
        contractName: [{ required: true, message: '请输入合同名称!', trigger: 'blur' }],
        procurementType: [{ required: true, message: '请选择采购类型!', trigger: ['blur', 'change'] }],
				signFile: [{ required: false, message: '请上传用印文件!' }],
				applyTeam: [{ required: true, message: '请选择申请人所属团队!' }],
      },
			isSubmit:false,
			flowCode: 'dev_erp_purchase_contract_001',
			formUrl: "/erp/purchase/contract/modules/ErpPurchaseContractForm",
			processId: '',
			beanName: 'erpPurchaseContractServiceImpl',
			formUrlMobile: '/pages/synergy/erpPurchaseContractList',
    }
  },
  onLoad({ id }) {
    this.id = id || ''
		if (this.id) {
		  this.initInfo()
		} else {
		  this.initForm()
		  this.initBillNo()
		}
  },
  computed: {
    ...mapState(['userInfo']),
    totalMoney() {
      return this.paymentFormData.reduce((total, item) => total + Number(item.paymentAmount), 0).toFixed(2)
    },
		isDisabled: function () {
			if (this.materialFormData && this.materialFormData.length) {
				return true
			} else {
				return false
			}
		}
  },
  methods: {
	  // 跳转到完善非正式供应商信息
		getUnSupplier(){
			
			uni.navigateTo({
				url:'/pages/purchase/components/unSupplierForm'
			})
			
		},
		onJudge(){
			// 保存返回的监听，事先处理好
			uni.$on("supplierBack", res => {
				
				this.supplyCompanBack(res)
				
				// 清除监听
				uni.$off('supplierBack');
			})
			
			uni.navigateTo({
				url:'/pages/common/selectSupplier/selectSupplierInput'
			})
		},
		handleCheck(detail){
			this.materialFormData.map(val => {
				val.checked = !!detail.length
				return val
			})
			if(detail.length){
				this.materialFormData.map((val,index) => {
					this.deleteCheck.push(val.id)
				})
			} else {
				this.deleteCheck = []
			}
			this.$forceUpdate()
		},
		// 是否定点
		isFixedTimeInput (val) {
			this.$set(this.model, 'expireTime', null)
			this.$refs.form.clearValidate('expireTime');
		},
		childCheck(detail){
			this.deleteCheck = detail
			this.materialFormData.map(val => {
				val.checked = this.deleteCheck.includes(val.id)
				return val
			})
			if(detail.length == this.materialFormData.length){
				this.materialChecked = ['']
			} else {
				this.materialChecked = []
			}
			this.$forceUpdate()
		},
		deleteAllMaterial(){
			const that = this
			uni.showModal({
				content: '确定删除吗？',
				success: res => {
					if (res.confirm) {
						this.materialFormData = this.materialFormData.filter((i) => {
							return !this.deleteCheck.includes(i.id)
						})
						this.deleteCheck = []
						this.materialChecked = []
					}
				}
			});
		},
		// 数组对象去重
		arrHeavy (arr) {
			let newobj = {}
			arr = arr.reduce((preVal, curVal) => {
				newobj[curVal.materialBillId] ? '' : newobj[curVal.materialBillId] = preVal.push(curVal);
				return preVal
			}, [])
			return arr
		},
		contactBack(data){
			data.map(value => {
				this.materialFormData.push(value)
			})
			this.materialFormData = this.arrHeavy(this.materialFormData)
		},
		cannibalizeInputBack(val){
			urlListDetail({ calibrationId: val }).then((res) => {
			 if (res.success) {
					this.materialFormData = []
					this.materialFormData = res.result
				}
			})
		},
		handleBalize(){
			if(this.isDisabled) return
			this.$refs.cannibalizeInput.showPopup = true
		},
		handleMenu(){
			this.$refs.applyFormInput.showPopup = true
		},
		handleRules(val){
			if(this.model.isUseSeal == '1'){
				this.$set(this.rules,'sealType',[{ required: true, message: '请选择印章类型!' }])
				this.$set(this.rules,'useSealNumber',[
		      { required: true, message: '请输入用印份数!', trigger: 'blur' },
		      { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
		    ])
			} else {
				this.$delete(this.rules,'sealType')
				this.$delete(this.rules,'useSealNumber')
				this.$set(this.model,'sealType','')
				this.$set(this.model,'useSealNumber','')
				this.$set(this.model, 'signSealWay', '') // 置空电子签章
			}
		},
		
		// 选择电子签章
		handleSignSealWay (val) {
			if (val == 'online') {
				this.rules.signFile[0].required = true
			} else {
				this.rules.signFile[0].required = false
			}
			this.$set(this.model, 'isSignSeal', '0') // 对方是否电子签章默认为否
			this.$set(this.model, 'psnName', '')
			this.$set(this.model, 'psnMobile', '')
			this.$set(this.model, 'supplyPsnName', '')
			this.$set(this.model, 'supplyPsnMobile', '')
		},
		// 点击对方是否为电子签章
		isSignSealInput () {
			this.$set(this.model, 'supplyPsnName', '')
			this.$set(this.model, 'supplyPsnMobile', '')
		},
    // 需方选择往来单位
    demandCompanNameInput(dataBack) {
      // this.$refs.form.clearValidate('demandCompanyAddress')
      // this.$refs.form.clearValidate('demandRegistrationNumber')
      // this.$refs.form.clearValidate('demandBankName')
      // this.$refs.form.clearValidate('demandBankAccountNo')
      if (dataBack) {
        this.$set(this.model, 'demandCompanyAddress', dataBack.enterpriseAddress) // 公司地址
        this.$set(this.model, 'demandRegistrationNumber', dataBack.enterpriseCreditCode) // 纳税人识别号
        this.$set(this.model, 'demandBankName', dataBack.bankName) // 开户行
        this.$set(this.model, 'demandBankAccountNo', dataBack.bankAccountNo) // 银行账户
      } else {
        this.$set(this.model, 'demandCompanyAddress', null) // 公司地址
        this.$set(this.model, 'demandRegistrationNumber', null) // 纳税人识别号
        this.$set(this.model, 'demandBankName', null) // 开户行
        this.$set(this.model, 'demandBankAccountNo', null) // 银行账户
      }
    },
    teamBack(item) {
      if (!!this.model.teamId && item) {
        if (this.teamIdBackups !== item.id && !!this.model.projectId) {
          this.$set(this.model, 'projectId', null)
        }
        this.teamIdBackups = item.id
      }
    },
    // 供方选择往来单位
    supplyCompanBack(dataBack) {
		
		// this.officialType = dataBack.officialType
	  this.$set(this.model, 'supplyCompanName', dataBack.id) 
	  
      this.$set(this.model, 'supplyCompanyAddress', dataBack.enterpriseAddress) // 公司地址
      this.$set(this.model, 'supplyBankName', dataBack.bankName) // 开户银行
      this.$set(this.model, 'supplyBankAccountNo', dataBack.bankAccountNo) // 银行账号
      this.$set(this.model, 'supplyRegistrationNumber', dataBack.enterpriseCreditCode) // 纳税人识别号
    },
    // 税率输入框变化时
    inputTaxRateBlur(value) {
      let item = this.model.taxRate.toString().slice(0, 2)
      let data = this.model.taxRate.toString().replace(/\b(0+)/gi, '')
      if (this.model.invoiceCategory !== '0' && item !== '0.') {
        // 去除0
        var num = data
      }
      if (data == '.') {
        this.$set(this.model, 'taxRate', null)
      }
      if (num >= 0 && num < 100) {
        this.$set(this.model, 'taxRate', num)
      }
      if (num < 0) {
        this.$set(this.model, 'taxRate', '0')
      }
      if (num >= 100) {
        this.$set(this.model, 'taxRate', '100')
      }
      if (this.model.totalAmount) {
        // 税费=合同额/（1+税率）* 税率
        var money = new Decimal(this.model.totalAmount)
          .div(new Decimal(1).add(new Decimal(this.model.taxRate).div(new Decimal(100))))
          .mul(new Decimal(this.model.taxRate).div(new Decimal(100)))
        this.$set(this.model, 'expensesTaxation', money.toFixed(2))
      }
      // this.$refs.form.clearValidate('expensesTaxation')
    },
		
		// 采购类型
		handleChangeProvisionType (val) {
			if (val == '1') {
				this.$set(this.rules, 'associationBillId', [{ required: true, message: '请选择关联单据!' }]);
				//清除采购申请单数据及校验
				this.$set(this.model, 'associationBillId', null);
			} else if (val == '2') {
				this.$set(this.rules, 'associationBillId', [{ required: true, message: '请选择关联单据!' }]);
				this.$set(this.model, 'associationBillId', null);
			}else if(val == '3'){
				this.$set(this.rules, 'associationBillId', [{ required: true, message: '请选择关联单据!' }]);
				//清除采购申请单数据及校验
				this.$set(this.model, 'associationBillId', null);
			}else {
				//清除关联单据ID数据及校验
				this.$set(this.model, 'associationBillId', null);
				this.$delete(this.rules, 'associationBillId');
			}
		},
		
    invoiceCategoryBlur(value) {
      this.$refs.form.clearValidate('taxRate')
      if (value == 0) {
        this.$set(this.model, 'taxRate', '0')
      } else {
        this.$set(this.model, 'taxRate', null)
      }
      this.$set(this.model, 'expensesTaxation', '0')
    },
		calTotalMoney () {
			var money = 0
			if (!!this.paymentFormData && this.paymentFormData.length) {
				this.paymentFormData.map(item => {
				money = money + Number(item.paymentAmount)
			})
			} else {
				money = 0
			}
			return money.toFixed(2)
		},
    handleEditPaymentForm([item, index]) {
      this.basicPaymentForm = { ...item }
      this.index = index
      this.showPaymentForm = true
			var ratioPayment = this.calculateRatioPayment() - Number(item.ratioPayment)
			this.$nextTick(() => {
				this.openPaymentForm(ratioPayment)
			})
    },
    handleRemovePaymentForm(item) {
      this.paymentFormData = this.paymentFormData.filter((i) => i !== item)
    },
    closePaymentForm() {
      this.$refs.dataPaymentForm.reset()
      this.basicPaymentForm = {}
      this.index = null
			this.showPaymentForm = false
    },
    openPaymentForm(value) {
			this.$refs.dataPaymentForm.basicForm = Object.assign({},this.basicPaymentForm)
			this.$nextTick(() => {
				this.$refs.dataPaymentForm.calculateRatioPayment(value)
			})
    },
    addPaymentForm() {
      this.index = null
			this.basicPaymentForm = {}
      this.showPaymentForm = true
			this.$nextTick(() => {
				this.openPaymentForm(this.calculateRatioPayment())
			})
    },
    handlePaymentFormSubmit([data, index]) {
      this.showPaymentForm = false
      if (typeof index === 'number') {
        this.$set(this.paymentFormData, index, data)
      } else {
        this.paymentFormData.push(data)
      }
			this.$set(this.model, 'totalAmount', this.calTotalMoney())
    },
    handleEditMaterialForm([item, index]) {
      this.basicMaterialForm = { ...item }
      this.index = index
      this.showMaterialForm = true
			this.$nextTick(() => {
				this.openMaterialForm()
			})
    },
    handleRemoveMaterialForm(item) {
      this.materialFormData = this.materialFormData.filter((i) => i !== item)
			this.$set(this.model, 'totalAmount', this.calTotalMoney())
    },
    closeMaterialForm() {
      this.$refs.dataMaterialForm.reset()
      this.basicMaterialForm = {}
      this.index = null
			this.showMaterialForm = false
    },
    openMaterialForm() {
      this.$refs.dataMaterialForm.basicForm = Object.assign({},this.basicMaterialForm)
			this.$refs.dataMaterialForm.firstClick = 1
			this.$refs.dataMaterialForm.provisionBroadChange()
    },
    addMaterialForm() {
      this.index = null
			this.basicMaterialForm = {}
      this.showMaterialForm = true
    },
    handleMaterialFormSubmit([data, index]) {
      this.showMaterialForm = false
      if (typeof index === 'number') {
        this.$set(this.materialFormData, index, data)
      } else {
        this.materialFormData.push(data)
      }
			if(!this.deleteCheck.includes(data.id)){
				this.materialChecked = []
			}
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo()
      this.model.purchaseBill = res.result
      // this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.purchaseBill //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
			this.$set(this.model, 'deliveryTimeUnit', '3')
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
			if (this.model && this.model.isUseSeal !== null) {
				this.model.isUseSeal = this.model.isUseSeal + ''
			}
			const resA = await queryByIdPurchaseContractPayAllList({ billId: this.model.id })
			this.paymentFormData = resA.result.records || resA.result
			const resB = await queryByIdPurchaseContractSuppliesAllList({ billId: this.model.id })
			this.materialFormData = resB.result.records || resB.result
			this.handleRules(this.model?.isUseSeal)
			const keys = ['expensesTaxation','sfyz','taxRate']
			keys.forEach(val => {
				if(typeof this.model[val] == 'number'){
					this.model[val] = String(this.model[val])
				}
			})
    },
		// 计算付款比例
		calculateRatioPayment () {
			var ratioPayment = 0
			if (this.paymentFormData && this.paymentFormData.length) {
				this.paymentFormData.map(value => {
					ratioPayment = Number(value.ratioPayment) - 0 + Number(ratioPayment)
				})
			}
			return ratioPayment
		},
    validateForm() {
      return this.$refs.form.validate().then(async () => {
        if (this.paymentFormData.length === 0) {
          this.$u.toast('请添加付款信息！')
          return Promise.reject()
        }
				
				if (this.calculateRatioPayment() < 100) {
				  this.$u.toast('付款信息中付款比例之和没有达到100%！')
				  return Promise.reject()
				}
				
				if (this.materialFormData.length === 0) {
				  this.$u.toast('请添加物料信息！')
				  return Promise.reject()
				}
				
				for (var i = 0; i < this.materialFormData.length; i++) {
					if (!this.materialFormData[i].unitPrice) {
						this.$u.toast('请输入物料信息单价！');
						return Promise.reject()
					}
				}
				
        if (!this.model.deliveryTimeUnit) {
					this.$u.toast('请选择货期单位！');
					return Promise.reject()
				}
        
        return Promise.resolve()
      })
    },
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		},
    async onSubmit() {
      await this.validateForm()
			let url = ''
			if (this.id) {
				url = await edit
			} else {
				url = await add
			}
			this.model.bpmBizTitle = this.model.contractName || ''
			try {
				this.isSubmit = true
				const response = await url({
					...this.model,
					purchaseContractPayments: this.paymentFormData,
					purchaseContractSupplies: this.materialFormData,
				})
				this.$u.toast(response.message)
				if (response.success) {
					if (this.model.id) {
						await this.getProcessList(this.model.id)
					} else {
						// 判断添加的时候是否有返回id值
						if (response.result) {
							await this.getProcessList(response.result)
						}
					}
				}
			}  finally {
				// error
			}
    },
    async onDraft() {
      // await this.validateForm()
			this.isSubmit = true
			this.model.bpmBizTitle = this.model.contractName || ''
			try {
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
			  const response = await url({
			    ...this.model,
			    purchaseContractPayments: this.paymentFormData,
			    purchaseContractSupplies: this.materialFormData,
			  })
			  if (response.success) {
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							this.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
			  }
			} finally {
				// error
			}
    },
  },
  watch: {
		// 监听税费
		'model.totalAmount': {
			handler (val) {
				this.$nextTick(() => {
					if (val && this.model.taxRate) {
						// 税费=合同额/（1+税率）* 税率
						var money = new Decimal(this.model.totalAmount).div(new Decimal(1).add(new Decimal(this.model.taxRate).div(new Decimal(100)))).mul(new Decimal(this.model.taxRate).div(new Decimal(100)))
						this.$set(this.model, 'expensesTaxation', money.toFixed(2))
					} else {
						this.$set(this.model, 'expensesTaxation', '0')
					}
				})
			},
			immediate: true,
			deep: true
		}
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
.basic-flex{
	display: flex;
	align-items: center;
	justify-content: space-between;
	.trip-form-notice{
		font-size: 28rpx;
		color: rgba(0, 0, 0, 0.7);
	}
}
</style>
